//
//  UIView+Badge.m
//  Common
//
//  Created by guoshiqing on 2018/6/12.
//  Copyright © 2018年 www.bitkinetic.com. All rights reserved.
//

#import "UIView+Badge.h"

#define TabbarItemNums 5.0    //tabbar的数量 如果是5个设置为5.0

@implementation UIView (Badge)

//显示小红点
- (void)showBadgeOnItemIndex:(NSInteger)index{
    
    // 如果小红点不存在，就新建小红点，如果已经存在就显示出来
    if (![self isExistBadgeOnItemIndex:index]) {
        //新建小红点
        UIView *badgeView = [[UIView alloc]init];
        badgeView.tag = 10+index;
        badgeView.layer.cornerRadius = 4.5f;//圆形
        badgeView.backgroundColor = [UIColor redColor];//颜色：红色
        CGRect tabFrame = self.frame;
        
        //确定小红点的位置(这里的index要按顺序来)
        float percentX = (index + 0.65) / TabbarItemNums;
        CGFloat x = ceilf(percentX * tabFrame.size.width);
        CGFloat y = ceilf(0.1 * tabFrame.size.height);
        badgeView.frame = CGRectMake(x, y, 9.0f, 9.0f);//圆形大小为10
        [self addSubview:badgeView];
    }
}

//隐藏小红点
- (void)hideBadgeOnItemIndex:(NSInteger)index{
    
    //按照tag值进行隐藏
    for (UIView *subView in self.subviews) {
        if (subView.tag == 10+index) {
            subView.hidden = YES;
        }
    }
}

// 查找小红点是否存在，并设置为显示
- (BOOL)isExistBadgeOnItemIndex:(NSInteger)index
{
    //按照tag值进行移除
    for (UIView *subView in self.subviews) {
        if (subView.tag == 10+index) {
            subView.hidden = NO;
            return YES;
        }
    }
    return NO;
}


////////////////////////////////////////////////////////

- (void)showBadge
{
    // 如果小红点不存在，就新建小红点，如果已经存在就显示出来
    if (![self isExistBadge]) {
        // 新建小红点
        UIView *badgeView = [[UIView alloc]init];
        badgeView.tag = 10;
        badgeView.layer.cornerRadius = 3.0f;//圆形
        badgeView.backgroundColor = [UIColor redColor];//颜色：红色
        CGRect tabFrame = self.frame;
        
        // 确定小红点的位置
        CGFloat x = ceilf(self.frame.size.width - badgeView.frame.size.width - 9.0f);
        CGFloat y = ceilf(0.2 * tabFrame.size.height);
        badgeView.frame = CGRectMake(x, y, 6.0f, 6.0f);//圆形大小为10
        [self addSubview:badgeView];
    }
}
- (void)hideBadge
{
    //按照tag值进行隐藏
    for (UIView *subView in self.subviews) {
        if (10 == subView.tag) {
            subView.hidden = YES;
        }
    }
}

- (BOOL)isExistBadge
{
    //按照tag值进行移除
    for (UIView *subView in self.subviews) {
        if (10 == subView.tag) {
            subView.hidden = NO;
            return YES;
        }
    }
    return NO;
}



@end
